<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;
ini_set('allow_call_time_pass_reference','On');
ainclude('include|acl');

// With this class we separate backend and frontend controllers but keep common functions
class AgoraCommonController {

	function AgoraCommonController() {
		$this->__construct();
	}

	function __construct() {
		$board = & Model::getInstance('BoardModel');
		$this->forumList = $board->loadForumList();
		$this->writableForumList = $board->loadForumList(true, 'post_topic');
		$this->config = & Model::getInstance('ConfigModel');
		$this->agora_config = $this->config->load();
	}

	function redirect() {
		$task = Agora::getVar('task',null);
		$page = Agora::getVar('page',null);
		//$action = Agora::getVar('action',null);

		$url = array();

		if ($task) $url['task'] = $task;
		if ($page) $url['page'] = $page;
		//elseif ($action) $url['action'] = $action;

		$args =  func_get_args();
		
		foreach ($args as $arg) {
			
			if (strpos($arg,'!') === 0) {
				unset($url[substr($arg,1)]);
				continue;
			}

			if (strpos($arg,'=') !== FALSE) {
				list($param,$value) = explode('=',$arg,2);
				$url[$param] = $value;
				continue;
			}

			$val = Agora::getRequestVar($arg,null);

			if ($val) {
				$url[$arg] = $val;
			}
		}
		
		//preserve pagination
		
		$p = Agora::getVar('p');
		if (!empty($p) && 1 < intval($p)) {
			$url['p'] = $p;
		}
		
		if (isset($url['type']) && $url['type'] == 'clean') {
			Agora::redirect(Agora::makeURL($url), true);
		} else {
			Agora::redirect(Agora::makeURL($url), false);
		}
	}

	function loadView($class,$file) {
		ainclude ("view|$file");
		$this->view = new $class;
		$this->_prepareView();
	}

	function _prepareView() {
		$this->view->assignRef('forums',$this->forumList);
		$this->view->assignRef('writable_forums',$this->writableForumList);
		$this->view->assign('agora_config', $this->agora_config);
		$this->view->assign('current_version',AGORA_VERSION);
	}

	function display($template = NULL) {
		if (!property_exists($this, 'view')) return;
		$this->view->display($template);
	}

	function _execute() {
		$this->display();
	}

}

class AgoraController extends AgoraCommonController {
	var $user;
	var $config;
	var $view;
	var $agora_user;
	var $access_model;

	function __construct() {
	
		parent::__construct();

		$this->user = & Model::getInstance('UserModel');
		$this->view = NULL;
		$this->agora_user = $this->user->loadCurrent();
		
		if (Agora::getSessionVar('sync_performed') == NULL) {
			$this->user->sync();
			Agora::setSessionVar('sync_performed',1);
		}

		$this->access_model = & Model::getInstance('AccessModel');
		$role = $this->access_model->getRole($this->agora_user['id'],1);
		
		$this->ban_model = & Model::getInstance('BanModel');
		$this->banned = $this->ban_model->isBanned($this->agora_user['username']);
		
		switch ($role) {
			case AGORA_ROLE_ADMIN:
					$this->agora_user['is_admin'] = true;
					$this->agora_user['is_moderator'] = true;
					$this->agora_user['is_member'] = true;
					$this->agora_user['is_guest'] = false;
					break;
			case AGORA_ROLE_MODERATOR:
					$this->agora_user['is_admin'] = false;
					$this->agora_user['is_moderator'] = true;
					$this->agora_user['is_member'] = true;
					$this->agora_user['is_guest'] = false;
					break;
			case AGORA_ROLE_MEMBER:
					$this->agora_user['is_admin'] = false;
					$this->agora_user['is_moderator'] = false;
					$this->agora_user['is_member'] = true;
					$this->agora_user['is_guest'] = false;
					break;
			case AGORA_ROLE_GUEST:
			default:
					$this->agora_user['is_admin'] = false;
					$this->agora_user['is_moderator'] = false;
					$this->agora_user['is_member'] = false;
					$this->agora_user['is_guest'] = true;
					break;
		}

		if (!array_key_exists('is_superadmin', $this->agora_user) || !$this->agora_user['is_superadmin']) {
			foreach ($this->forumList as $cat_id => $cat) {
				$this->access_model->filterForums($this->forumList[$cat_id]['forums'],$this->agora_user['id']);
				foreach ($this->forumList[$cat_id]['forums'] as $forum_id=>$forum) {
					$parent_id = $forum['parent_forum_id'];
					if ($parent_id == 0) continue;
					if (!isset($this->forumList[$cat_id]['forums'][$parent_id])) {
						unset($this->forumList[$cat_id]['forums'][$forum_id]);
					}
				}

				if (empty($this->forumList[$cat_id]['forums'])) {
					unset($this->forumList[$cat_id]);
				}
			}
		}

	}

	function authenticate($forum_id, $access) {
		if (array_key_exists('is_superadmin', $this->agora_user) && $this->agora_user['is_superadmin']) return true;
		if (!is_numeric($forum_id) || !$this->access_model->authenticate($this->agora_user['id'],$forum_id,$access) || ($this->banned && !in_array($access,array('bbcode_img','bbcode','read','read_rss'))) ) {
			Agora::showMessage(Agora::lang('Access denied'));
			//Agora::redirect(Agora::getRefferer());
			Agora::redirect(Agora::makeURL(array()));
		}
		
	}

	function authenticateTopic($topic_id, $access) {
		if ($this->agora_user['is_superadmin']) return true;
		if (!is_numeric($topic_id) || !$this->access_model->authenticateTopic($this->agora_user['id'],$topic_id,$access) || ($this->banned && !in_array($access,array('bbcode_img','bbcode','read','read_rss'))) ) {
			Agora::showMessage(Agora::lang('Access denied'));
			//Agora::redirect(Agora::getRefferer());
			Agora::redirect(Agora::makeURL(array()));
		}
	}

	function authenticatePost($post_id, $access) {
		if ($this->agora_user['is_superadmin']) return true;
		if (!is_numeric($post_id) || !$this->access_model->authenticatePost($this->agora_user['id'],$post_id,$access) || ($this->banned && !in_array($access,array('bbcode_img','bbcode','read','read_rss'))) ) {
			Agora::showMessage(Agora::lang('Access denied'));
			//Agora::redirect(Agora::getRefferer());
			Agora::redirect(Agora::makeURL(array()));
		}
	}

	function & helper($name) {
		static $loaded;
		if (!isset($loaded[$name])) {
			ainclude('helpers|'.$name);
			$classname = 'A'.ucfirst($name).'Helper';
			$helper = new $classname;
			$loaded[$name] = & $helper;

			$helper->agora_config = property_exists($this, 'agora_config') ? $this->agora_config : null;
			$helper->agora_user = $this->agora_user;
			$helper->controller = $this;
			if (method_exists($helper,'assign')) {
				$helper->assign($this->view);
			}
		}

		return $loaded[$name];
	}

	function _prepareView() {
		parent::_prepareView();

		if (isset($this->agora_config['o_rss_cron_builtin']) && $this->agora_config['o_rss_cron_builtin'] == '1') {
			if (time() - $this->agora_config['o_rss_cron_interval'] > $this->agora_config['o_rss_cron_last']) {
				$feed_model = & Model::getInstance('AggregatorModel');
				$feed_model->runJob();
				$conf['o_rss_cron_last'] = time();
				$this->config->save($conf);
			}
		}
		
		/*
		if (isset($this->agora_config['o_emailpsw_perhour']) && (int)$this->agora_config['o_emailpsw_perhour'] == $this->agora_config['o_emailpsw_perhour']) 
		{
				$user_model = & Model::getInstance('UserModel');
				$user_model->sendNewPasswrds($this->agora_config['o_emailpsw_perhour']);
		}
		*/
		
		$stats = & Model::getInstance('StatModel');
		$online = & Model::getInstance('OnlineModel');

		if (!$this->agora_user['is_guest']) {
			if ($this->agora_config['o_pms_uddeim'] == '1') {
				$pm_model = & Model::getInstance('UddePMModel');
				$message_count = $pm_model->getUnreadCount($this->agora_user['jos_id']);
			} else {
				$pm_model = & Model::getInstance('PMSModel');
				$message_count = $pm_model->getUnreadCount($this->agora_user['id']);
			}
			$this->view->assign('pm_count',$message_count);
		}
		
		if ($this->agora_user['is_superadmin'] || $this->agora_user['is_admin'] || $this->agora_user['is_moderator']) {
			$allowed = $this->access_model->getAllowedForums($this->agora_user['id'], 'post_approve');
			$mod_model = & Model::getInstance('ModerationModel');
			$mod_model->_setAllowedForumsArr($allowed);
			$mod_model->_setAllowedForums();
			$mod_model->_setSuperAdmin($this->agora_user['is_superadmin']);
			$num_posts = $mod_model->countUnapproved();
			$num_topics = $mod_model->countUnapproved(0);
			$num_all = ((int)$num_posts + (int)$num_topics);
			$this->view->assign('num_unapproved_posts',$num_posts);
			$this->view->assign('num_unapproved_topics',$num_topics);
			$this->view->assign('num_unapproved_all',$num_all);
		}

		$this->view->assign('action', Agora::getVar('task','index'));
		$this->view->assign('agora_itemid', Agora::getVar('Itemid',''));
		$this->view->assign('agora_user', $this->agora_user);
		$this->view->assign('stats',$stats->getStats());
		$this->view->assign('online_users',$online->getOnline());

		$defview = Agora::getSessionVar('defaultview');
		if (!$defview) {
			Agora::setSessionVar('view',$this->agora_config['o_default_view']);
			Agora::setSessionVar('defaultview','1');
		}

		$view = Agora::getSessionVar('view','forum');

		if ($view === 'forum') {
			$this->view->assign('forum_view',1);
		} else {
			$this->view->assign('forum_view',0);
		}

		if ($this->agora_user['id']) {
			$ag_model = & Model::getInstance('AgoraGroupsModel');
			if ($ag_model->IsInstalled()) {
				$ag_groups = $ag_model->getUserGroups($this->agora_user['id']);
				$this->view->assign('ag_groups',$ag_groups);
			}
		}

		if ($this->agora_config['o_top_ten']) {
			$user_model = & Model::getInstance('UserModel');
			$this->view->assign('top_users',$user_model->getTop($this->agora_config['o_top_post_count']));
		}
	}

	function loadDefaultView($template = NULL, $view='view') {
		ainclude ("view|$view");

		if (Agora::isFeed()) {
			ainclude ('view|feedview');
			$this->view = new FeedView($template);
		} else {
			$this->view = new View($template);
			$this->_prepareView();
		}
	}

	function setPagination($page_count, $navlinks = true) {
		$current_page = Agora::getPage($page_count);
		$first = Agora::lang('First');
		$last = Agora::lang('Last');

		$url = Agora::getSelf();
		//remove old pagination
		$url = preg_replace('/[\?&]?p=\d+/','',$url);


		if (strpos($url,'?') === FALSE) {
			$url .= '?';
		} else {
			if (substr($url, -1)!=='&')
			{
				$url .= '&';
			}
		}

		$pages = array();

		$this->view->smarty->assign_by_ref('pagination',$pages);

		if ($page_count <= 1) {
			$pages[] = array('caption'=>'1','url'=>'');

			return;
		}

		if ($current_page > 3) {
			$pages[] = array('caption'=>'1','url'=>Agora::routeURL($url));

			if ($current_page != 4)
				$pages[] = array('caption' => '&hellip;','url'=>'');
		}

		for ($p = $current_page - 2; $p <= $current_page + 2; $p++) {
			if ($p < 1 || $p > $page_count) {
				continue;
			}

			if ($current_page == $p) {
				$pages[] = array('caption'=>strval($p),'url' =>'');
			} elseif ($p == 1) {
				if (substr($url, -1)=='&') {
					$pages[] = array('caption'=>strval($p),'url' => Agora::routeURL(substr($url, 0, strlen($url)-1)));
				} else {
					$pages[] = array('caption'=>strval($p),'url' => Agora::routeURL($url));
				}
			} else {
				$pages[] = array('caption'=>strval($p),'url' => Agora::routeURL($url . "p=$p"));
			}
		}

		if ($current_page <= $page_count - 3) {
			if ($current_page != $page_count-3) {
				$pages[] = array('caption' => '&hellip;', 'url' => '');
			}

			$pages[] = array('caption'=>strval($page_count),'url'=> Agora::routeURL($url . "p=$page_count"));

		}
		
		if (!$navlinks) return;

		if ($current_page > 1) {
			//prepend
			$back = $current_page;
			--$back;
			array_unshift($pages,array('caption'=>'&laquo;','url'=>Agora::routeURL($url . "p=$back" )));
			if (substr($url, -1)=='&') {
				array_unshift($pages,array('caption'=>$first,'url'=>Agora::routeURL(substr($url, 0, strlen($url)-1))));
			} else {
				array_unshift($pages,array('caption'=>$first,'url'=>Agora::routeURL($url)));
			}
		}

		if ($current_page < $page_count) {
			$forward = $current_page;
			++$forward;
			$pages[] = array('caption'=>'&raquo;','url'=>Agora::routeURL($url . "p=$forward"));
			$pages[] = array('caption'=>$last,'url'=>Agora::routeURL($url . "p=$page_count"));
		}

	}
}
